let Product = require('../../db/productSchma');
// 引入form表单解析中间件
let formidable = require('formidable');
let path = require('path');

let form = formidable({
    keepExtensions: true,
    uploadDir: path.join(__dirname, '../', '../', 'public', 'uploads')
});
module.exports = (req, res) => {
    // console.log(req.params.productId);
    // console.log(req.body.productId);

    form.parse(req, async(err, fields, files) => {
        if (err) {
            res.status(500).send(err);
        } else {
            // 创建商品信息添加到数据库中
            // 如果不修改文件图片, 及描述区域将空白提交
            if (!files.pic.originalFilename) {
                var addRel = await Product.updateOne({ "_id": req.params.productId }, {
                    title: fields.title,
                    cate_id: fields.cate_id,
                    goods_id: fields.goods_id,
                    price: fields.price,
                    fee: fields.fee,
                    description: fields.description
                });
            } else {
                var addRel = await Product.updateOne({ "_id": req.params.productId }, {
                    title: fields.title,
                    cate_id: fields.cate_id,
                    goods_id: fields.goods_id,
                    price: fields.price,
                    fee: fields.fee,
                    description: fields.description,
                    pic: files.pic.filepath.split("public")[1]
                });
            };

            if (addRel) {
                res.redirect('/product/productlist');
            } else {
                res.status(500).send('添加失败');
            }

        };
    });
}